/**
 * Copyright 厦门中软海晟信息技术有限公司 版权所有 违者必究 2019
 */
package com.opencvjava.lessons2;

import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;
import org.springframework.stereotype.Service;

import java.awt.image.ImageProducer;

import static com.opencvjava.support.util.CvUtils.imshow;
import static com.opencvjava.support.util.CvUtils.mat;
import static org.opencv.imgproc.Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C;
import static org.opencv.imgproc.Imgproc.ADAPTIVE_THRESH_MEAN_C;
import static org.opencv.imgproc.Imgproc.THRESH_BINARY;
import static org.opencv.imgproc.Imgproc.THRESH_BINARY_INV;
import static org.opencv.imgproc.Imgproc.THRESH_OTSU;
import static org.opencv.imgproc.Imgproc.THRESH_TRIANGLE;
import static org.opencv.imgproc.Imgproc.adaptiveThreshold;
import static org.opencv.imgproc.Imgproc.threshold;

/**
 * @author : sunzb(sunzb@hsit.com.cn)
 * @date: 2019/1/14
 */
@Service
public class BinaryDemo {
    public void test() {
        Mat src = mat("lena.jpg");
        if (src.empty()) {
            throw new RuntimeException("图片读取失败");
        }
        imshow("源图", src);
        Mat gray = new Mat();
        Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
        imshow("灰度", gray);
        Mat dst = new Mat();
        // 生物细胞，文本 三角阈值法，适用于只有一个波峰 THRESH_TRIANGLE
        threshold(gray, dst, 127, 255, THRESH_BINARY | THRESH_TRIANGLE);
        imshow("三角二值化结果", dst);
        threshold(gray, dst, 127, 255, THRESH_BINARY | THRESH_OTSU);
        imshow("OTSU二值化结果", dst);

        adaptiveThreshold(gray, dst, 255,
                ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 5, 10);
        imshow("自适应均值二值化", dst);
        adaptiveThreshold(gray, dst, 255,
                ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 5, 10);
        imshow("自适应高斯二值化5", dst);
        adaptiveThreshold(gray, dst, 255,
                ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 15, 10);
        imshow("自适应高斯二值化15", dst);

        src = mat("text1.png");
        Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
        imshow("源图2", src);
        threshold(gray, dst, 127, 255, THRESH_BINARY_INV | THRESH_OTSU);
        imshow("OTSU二值化结果", dst);
        adaptiveThreshold(gray, dst, 255,
                ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY_INV, 15, 10);
        imshow("自适应高斯二值化15", dst);
        adaptiveThreshold(gray, dst, 255,
                ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY_INV, 55, 10);
        imshow("自适应高斯二值化55", dst);
    }
}
